package com.dz.lm.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @description 身份证工具类
 * @author zhang-hr
 */
public class IdCardUtil {
    public static final int CHINA_ID_MAX_LENGTH = 18;
    /** 每位加权因子 */
    public static final int power[] = {
            7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2
    };
	/**
	 * 根据身份证号码，返回年龄
	 * 
	 * @param idCardNo
	 *            身份证号
	 * @return
	 */
	public static int parseAge(String idCardNo) {
		int age = 0;
		String birthDayStr = idCardNo.substring(6, 14);
		Date birthDay = null;
		try {
			birthDay = new SimpleDateFormat("yyyyMMdd").parse(birthDayStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH) + 1;
		int dayNow = cal.get(Calendar.DAY_OF_MONTH);
		cal.setTime(birthDay);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH) + 1;
		int dayBirth = cal.get(Calendar.DAY_OF_MONTH);
		age = yearNow - yearBirth;
		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth && dayNow < dayBirth) {
				age--;
			}
		} else {
			age--;
		}
		return age;
	}
	
    /**
     * 验证18位身份编码是否合法
     * 
     * @param idCard 身份编码
     * @return 是否合法
     */
    public static boolean validateIdCard(String idCard) {
        boolean bTrue = false;
        if (idCard.length() == CHINA_ID_MAX_LENGTH) {
            // 前17位
            String code17 = idCard.substring(0, 17);
            // 第18位
            String code18 = idCard.substring(17, CHINA_ID_MAX_LENGTH);
            if (isNum(code17)) {
                char[] cArr = code17.toCharArray();
                if (cArr != null) {
                    int[] iCard = converCharToInt(cArr);
                    int iSum17 = getPowerSum(iCard);
                    // 获取校验位
                    String val = getCheckCode18(iSum17);
                    if (val.length() > 0) {
                        if (val.equalsIgnoreCase(code18)) {
                            bTrue = true;
                        }
                    }
                }
            }
        }
        return bTrue;
    }
    
    /**
     * 数字验证
     * 
     * @param val
     * @return 提取的数字。
     */
    private static boolean isNum(String val) {
        return val == null || "".equals(val) ? false : val.matches("^[0-9]*$");
    }
    
    /**
     * 将字符数组转换成数字数组
     * 
     * @param ca
     *            字符数组
     * @return 数字数组
     */
    private static int[] converCharToInt(char[] ca) {
        int len = ca.length;
        int[] iArr = new int[len];
        try {
            for (int i = 0; i < len; i++) {
                iArr[i] = Integer.parseInt(String.valueOf(ca[i]));
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return iArr;
    }
    
    /**
     * 将身份证的每位和对应位的加权因子相乘之后，再得到和值
     * 
     * @param iArr
     * @return 身份证编码。
     */
    private static int getPowerSum(int[] iArr) {
        int iSum = 0;
        if (power.length == iArr.length) {
            for (int i = 0; i < iArr.length; i++) {
                for (int j = 0; j < power.length; j++) {
                    if (i == j) {
                        iSum = iSum + iArr[i] * power[j];
                    }
                }
            }
        }
        return iSum;
    }
    /**
     * 将power和值与11取模获得余数进行校验码判断
     * 
     * @param iSum
     * @return 校验位
     */
    private static String getCheckCode18(int iSum) {
        String sCode = "";
        switch (iSum % 11) {
        case 10:
            sCode = "2";
            break;
        case 9:
            sCode = "3";
            break;
        case 8:
            sCode = "4";
            break;
        case 7:
            sCode = "5";
            break;
        case 6:
            sCode = "6";
            break;
        case 5:
            sCode = "7";
            break;
        case 4:
            sCode = "8";
            break;
        case 3:
            sCode = "9";
            break;
        case 2:
            sCode = "x";
            break;
        case 1:
            sCode = "0";
            break;
        case 0:
            sCode = "1";
            break;
        }
        return sCode;
    }
    
    /**
     * 根据身份编号获取生日
     * 
     * @param idCard 身份编号
     * @return 生日(yyyyMMdd)
     */
    public static String getBirthByIdCard(String idCard) {
        return idCard.substring(6, 14);
    }
    
    /**
     * 根据身份编号获取性别
     * 
     * @param idCard 身份编号
     * @return 性别(1-男，0-女，2-未知)
     */
    public static String getGenderByIdCard(String idCard) {
        String sGender = "2";
        String sCardNum = idCard.substring(16, 17);
        if (Integer.parseInt(sCardNum) % 2 != 0) {
            sGender = "1";
        } else {
            sGender = "0";
        }
        return sGender;
    }
}
